#region Microsoft Public License
/*
 * (c) Copyright Chenjun Wu. http://utablesdk.codeplex.com
 * 
 * This source is subject to the Microsoft Public License (Ms-PL).
 * Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
 * All other rights reserved.
 */
#endregion

﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Windows.Controls;
using System.Windows;

namespace UTable.Objects.Controls
{
    public class ObservableUIElementCollection : UIElementCollection, INotifyCollectionChanged
    {
        public ObservableUIElementCollection(UIElement visualParent, FrameworkElement logicalElement) :
            base(visualParent, logicalElement)
        {
        }

        public override int Add(UIElement element)
        {
            int index = base.Add(element);
            OnCollectionChanged(NotifyCollectionChangedAction.Add, element, index);
            return index;
        }

        public override void Insert(int index, UIElement element)
        {
            base.Insert(index, element);
            OnCollectionChanged(NotifyCollectionChangedAction.Add, element, index);
        }

        public override void RemoveAt(int index)
        {
            UIElement element = null;
            if (index >= 0 && index < base.Count)
                element = base[index];
            base.RemoveAt(index);
            if (element != null)
                OnCollectionChanged(NotifyCollectionChangedAction.Remove, element, index);
        }

        public override void Remove(UIElement element)
        {
            int index = IndexOf(element);
            base.Remove(element);
            OnCollectionChanged(NotifyCollectionChangedAction.Remove, element, index);
        }

        public override void Clear()
        {
            List<UIElement> oldItems = new List<UIElement>();
            foreach (UIElement item in this)
            {
                oldItems.Add(item);
            }
            base.Clear();
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset, null, oldItems));
        }

        protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            NotifyCollectionChangedEventHandler collectionChanged = CollectionChanged;

            if (collectionChanged != null)
                collectionChanged(this, e);
        }

        void OnCollectionChanged(NotifyCollectionChangedAction action, object item, int index)
        {
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item, index));
        }

        public event NotifyCollectionChangedEventHandler CollectionChanged;
    }
}
